﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using VOL.Core.Controllers.Basic;
using VOL.System.IServices;
using System.Text.Json;

namespace VOL.WebApi.Controllers
{
  

    [AllowAnonymous, ApiController]
    [ApiExplorerSettings(GroupName = "v1")]
    [Route("api/[controller]")]
    public class GanttController : ApiBaseController<ISys_UserService>
    {
        [HttpGet]
        public IActionResult GetGanttData()
        {
            var data = GanttDataService.GetGanttData();

            // 转换为前端需要的格式
            var result = new
            {
                data = data.Data.Select(t => new
                {
                    id = t.Id,
                    text = t.Text,
                    start_date = t.StartDate.ToString("yyyy-MM-dd"),
                    duration = t.Duration,
                    progress = t.Progress,
                    parent = t.Parent,
                    type = t.Type,
                    priority = t.Priority,
                    assignee = t.Assignee,
                    description = t.Description
                }),
                links = data.Links.Select(l => new
                {
                    id = l.Id,
                    source = l.Source,
                    target = l.Target,
                    type = l.Type
                })
            };

            return Ok(result);
        }

        [HttpPost("task")]
        public IActionResult AddTask([FromBody] GanttTask task)
        {
            //if(task == null)
            //{  return BadRequest(); }
            //GanttDataService.AddTask(task);
            //return Ok(new { id = task.Id });

            try
            {
                if (task == null)
                {
                    return BadRequest("任务数据不能为空");
                }

                Console.WriteLine($"接收到任务数据: {JsonSerializer.Serialize(task)}");

                GanttDataService.AddTask(task);
                return Ok(new { id = task.Id });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加任务失败: {ex.Message}");
                return StatusCode(500, $"添加任务失败: {ex.Message}");
            }
        }

        [HttpPut("task/{id}")]
        public IActionResult UpdateTask(int id, [FromBody] GanttTask task)
        {
            task.Id = id;
            GanttDataService.UpdateTask(task);
            return Ok();
        }

        [HttpDelete("task/{id}")]
        public IActionResult DeleteTask(int id)
        {
            GanttDataService.DeleteTask(id);
            return Ok();
        }

        [HttpPost("link")]
        public IActionResult AddLink([FromBody] GanttLink link)
        {
            try
            {
                if (link == null)
                {
                    return BadRequest("链接数据不能为空");
                }

                Console.WriteLine($"接收到链接数据: {JsonSerializer.Serialize(link)}");

                GanttDataService.AddLink(link);
                return Ok(new { id = link.Id });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加链接失败: {ex.Message}");
                return StatusCode(500, $"添加链接失败: {ex.Message}");
            }
        }

        [HttpDelete("link/{id}")]
        public IActionResult DeleteLink(int id)
        {
            try
            {
                Console.WriteLine($"删除链接请求，ID: {id}");

                // 检查链接是否存在
                var existingLinks = GanttDataService.GetGanttData().Links;
                var link = existingLinks.FirstOrDefault(l => l.Id == id);

                if (link == null)
                {
                    Console.WriteLine($"链接不存在，ID: {id}");
                    return NotFound($"链接不存在，ID: {id}");
                }

                Console.WriteLine($"找到链接: {JsonSerializer.Serialize(link)}");
                GanttDataService.DeleteLink(id);
                Console.WriteLine($"链接删除成功，ID: {id}");
                return Ok();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除链接失败: {ex.Message}");
                return StatusCode(500, $"删除链接失败: {ex.Message}");
            }
        }
    }
    public class GanttDataService
    {
        private static readonly List<GanttTask> _tasks = new()
        {
            new GanttTask
            {
                Id = 1,
                Text = "项目启动",
                StartDate = DateTime.Parse("2024-03-01"),
                Duration = 3,
                Progress = 0.6m,
                Parent = 0,
                Type = "project",
                Priority = "high",
                Assignee = "项目经理",
                Description = "项目初始化和团队组建"
            },
            new GanttTask
            {
                Id = 2,
                Text = "需求分析",
                StartDate = DateTime.Parse("2024-03-04"),
                Duration = 5,
                Progress = 0.4m,
                Parent = 0,
                Type = "task",
                Priority = "high",
                Assignee = "需求分析师",
                Description = "收集和分析用户需求"
            },
            new GanttTask
            {
                Id = 3,
                Text = "系统设计",
                StartDate = DateTime.Parse("2024-03-09"),
                Duration = 7,
                Progress = 0.2m,
                Parent = 0,
                Type = "project",
                Priority = "medium",
                Assignee = "系统架构师",
                Description = "系统架构和详细设计"
            },
            new GanttTask
            {
                Id = 4,
                Text = "数据库设计",
                StartDate = DateTime.Parse("2024-03-09"),
                Duration = 3,
                Progress = 0.8m,
                Parent = 3,
                Type = "task",
                Priority = "medium",
                Assignee = "数据库工程师",
                Description = "数据库结构设计"
            },
            new GanttTask
            {
                Id = 5,
                Text = "界面设计",
                StartDate = DateTime.Parse("2024-03-12"),
                Duration = 4,
                Progress = 0.5m,
                Parent = 3,
                Type = "task",
                Priority = "medium",
                Assignee = "UI设计师",
                Description = "用户界面设计"
            },
            new GanttTask
            {
                Id = 6,
                Text = "开发阶段",
                StartDate = DateTime.Parse("2024-03-16"),
                Duration = 10,
                Progress = 0.1m,
                Parent = 0,
                Type = "project",
                Priority = "high",
                Assignee = "开发团队",
                Description = "系统开发实现"
            },
            new GanttTask
            {
                Id = 7,
                Text = "前端开发",
                StartDate = DateTime.Parse("2024-03-16"),
                Duration = 6,
                Progress = 0.3m,
                Parent = 6,
                Type = "task",
                Priority = "high",
                Assignee = "前端开发工程师",
                Description = "前端界面开发"
            },
            new GanttTask
            {
                Id = 8,
                Text = "后端开发",
                StartDate = DateTime.Parse("2024-03-16"),
                Duration = 8,
                Progress = 0.2m,
                Parent = 6,
                Type = "task",
                Priority = "high",
                Assignee = "后端开发工程师",
                Description = "后端服务开发"
            },
            new GanttTask
            {
                Id = 9,
                Text = "测试阶段",
                StartDate = DateTime.Parse("2024-03-26"),
                Duration = 5,
                Progress = 0.0m,
                Parent = 0,
                Type = "project",
                Priority = "medium",
                Assignee = "测试团队",
                Description = "系统测试和验证"
            },
            new GanttTask
            {
                Id = 10,
                Text = "单元测试",
                StartDate = DateTime.Parse("2024-03-26"),
                Duration = 3,
                Progress = 0.0m,
                Parent = 9,
                Type = "task",
                Priority = "medium",
                Assignee = "测试工程师",
                Description = "单元测试执行"
            },
            new GanttTask
            {
                Id = 11,
                Text = "集成测试",
                StartDate = DateTime.Parse("2024-03-29"),
                Duration = 2,
                Progress = 0.0m,
                Parent = 9,
                Type = "task",
                Priority = "medium",
                Assignee = "测试工程师",
                Description = "集成测试执行"
            },
            new GanttTask
            {
                Id = 12,
                Text = "部署上线",
                StartDate = DateTime.Parse("2024-03-31"),
                Duration = 2,
                Progress = 0.0m,
                Parent = 0,
                Type = "milestone",
                Priority = "high",
                Assignee = "运维工程师",
                Description = "系统部署和上线"
            }
        };

        private static readonly List<GanttLink> _links = new()
        {
            new GanttLink { Id = 1, Source = 1, Target = 2, Type = "0" },
            new GanttLink { Id = 2, Source = 2, Target = 3, Type = "0" },
            new GanttLink { Id = 3, Source = 3, Target = 4, Type = "0" },
            new GanttLink { Id = 4, Source = 4, Target = 5, Type = "0" },
            new GanttLink { Id = 5, Source = 5, Target = 6, Type = "0" },
            new GanttLink { Id = 6, Source = 6, Target = 7, Type = "0" },
            new GanttLink { Id = 7, Source = 6, Target = 8, Type = "0" },
            new GanttLink { Id = 8, Source = 7, Target = 9, Type = "0" },
            new GanttLink { Id = 9, Source = 8, Target = 9, Type = "0" },
            new GanttLink { Id = 10, Source = 9, Target = 10, Type = "0" },
            new GanttLink { Id = 11, Source = 10, Target = 11, Type = "0" },
            new GanttLink { Id = 12, Source = 11, Target = 12, Type = "0" }
        };

        public static GanttData GetGanttData()
        {
            return new GanttData
            {
                Data = _tasks,
                Links = _links
            };
        }

        public static GanttTask? GetTaskById(int id)
        {
            return _tasks.FirstOrDefault(t => t.Id == id);
        }

        public static void AddTask(GanttTask task)
        {
            task.Id = _tasks.Max(t => t.Id) + 1;
            _tasks.Add(task);

        }

        public static void UpdateTask(GanttTask task)
        {
            var existingTask = _tasks.FirstOrDefault(t => t.Id == task.Id);
            if (existingTask != null)
            {
                var index = _tasks.IndexOf(existingTask);
                _tasks[index] = task;
            }
        }

        public static void DeleteTask(int id)
        {
            var task = _tasks.FirstOrDefault(t => t.Id == id);
            if (task != null)
            {
                _tasks.Remove(task);
                // 删除相关的链接
                _links.RemoveAll(l => l.Source == id || l.Target == id);
            }
        }

        public static void AddLink(GanttLink link)
        {
            link.Id = _links.Max(l => l.Id) + 1;
            _links.Add(link);
        }

        public static void DeleteLink(int id)
        {
            var link = _links.FirstOrDefault(l => l.Id == id);
            if (link != null)
            {
                _links.Remove(link);
            }
        }
    }
    public class GanttTask
    {
        public int Id { get; set; }
        public string Text { get; set; } = string.Empty;
        public DateTime StartDate { get; set; }
        public int Duration { get; set; }
        public decimal Progress { get; set; }
        public int Parent { get; set; }
        public string Type { get; set; } = "task";
        public string Priority { get; set; } = "normal";
        public string Assignee { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
    }

    public class GanttLink
    {
        public int Id { get; set; }
        public int Source { get; set; }
        public int Target { get; set; }
        public string Type { get; set; } = "0";
    }

    public class GanttData
    {
        public List<GanttTask> Data { get; set; } = new List<GanttTask>();
        public List<GanttLink> Links { get; set; } = new List<GanttLink>();
    }
}
